<?php

namespace app\api\controller;

use app\admin\model\DormitoryDormBed;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use think\Validate;

/**
 * 用户接口
 * @package app\api\controller
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobileLogin', 'register', 'resetPwd', 'changeEmail', 'changeMobile', 'third' , 'check'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (用户中心)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 13:54)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/profile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564537957",
    "data": {
    "userinfo": {
    "id": 21,
    "username": "1234561001",
    "nickname": "张三",
    "mobile": "",
    "avatar": "",
    "score": 0,
    "token": "76df8852-a04e-4b1a-9d78-bf10afa5c5d8",
    "user_id": 21,
    "createtime": 1564537957,//token创建时间
    "expiretime": 1567129957,//token过期时间
    "expires_in": 2592000//token有效期
    }
    }
    })
     */
    public function profile()
    {
        $data['userinfo'] = $this->auth->getUserinfo();

        $data['userinfo']['bed'] = DormitoryDormBed::alias('bed')
            ->join('__DORMITORY_GARDEN__ garden', 'garden.number = bed.garden_number')
            ->join('__DORMITORY_BUILDING__ building', 'building.number = bed.building_number and building.garden_number = bed.garden_number')
            ->join('__DORMITORY_DORM__ dorm', 'dorm.number = bed.dorm_number and dorm.building_number = bed.building_number and dorm.garden_number = bed.garden_number')
            ->where('bed.student_id', $this->auth->target_id)
            ->field('bed.id,bed.number bed_number,bed.num bed_num,garden.name garden_name,building.name building_name,dorm.name dorm_name,CONCAT(dorm.floor, "层") dorm_floor')
            ->find();

        $this->success('', $data);
    }

    /**
     * @ApiTitle    (权限列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/9 10:37)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/ruleList)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function ruleList()
    {
        $data = $this->auth->getRuleList();

        $this->success('', $data);
    }

    /**
     * @ApiTitle    (检测是否是否有对应权限)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/13 15:43)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/check)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="path", type="string", required=true, description="控制器/方法", sample="")
     * @ApiParams   (name="module", type="string", required=true, description="模块 默认为当前模块", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function check()
    {
        $path = $this->request->request('path');
        $module = $this->request->request('module', null);

        $result = $this->auth->check($path, $module);

        $this->success('', $result);
    }

    /**
     * @ApiTitle    (用户登录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 10:27)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/login)
     * @ApiParams   (name="account", type="string", required=true, description="账号", sample="1234561001")
     * @ApiParams   (name="password", type="string", required=true, description="密码", sample="561001")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn   ({
    "code": 1,
    "msg": "登录成功",
    "time": "1564639763",
    "data": {
    "userinfo": {
    "id": 21,
    "username": "1234561001",
    "nickname": "张三",
    "mobile": "",
    "avatar": "data:image\/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgaGVpZ2h0PSIxMDAiIHdpZHRoPSIxMDAiPjxyZWN0IGZpbGw9InJnYigyMjQsMTYwLDIyOSkiIHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48L3JlY3Q+PHRleHQgeD0iNTAiIHk9IjUwIiBmb250LXNpemU9IjUwIiB0ZXh0LWNvcHk9ImZhc3QiIGZpbGw9IiNmZmZmZmYiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHRleHQtcmlnaHRzPSJhZG1pbiIgYWxpZ25tZW50LWJhc2VsaW5lPSJjZW50cmFsIj7lvKA8L3RleHQ+PC9zdmc+",
    "gender": 1,//1男 2女
    "birthday": null,//生日 date格式
    "score": 0,
    "token": "e960c343-84e3-4c28-9820-9742b0de3009",
    "user_id": 21,
    "createtime": 1564639764,//token创建时间
    "expiretime": 1567231764,//token过期时间
    "expires_in": 2592000//token有效期
    }
    }
    })
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @ApiTitle    (绑定手机号)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 10:49)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/bindMobile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "绑定成功",
    "time": "1564542858",
    "data": null
    })
     */
    public function bindMobile()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha)
            $this->error(__('Invalid parameters'));

        if (!Validate::regex($mobile, "^1\d{10}$"))
            $this->error(__('Mobile is incorrect'));

        if (!Sms::check($mobile, $captcha, 'bindmobile'))
            $this->error(__('Captcha is incorrect'));

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user)
            $this->error(__('手机号已存在'));

        $user = \app\common\model\User::find($this->auth->id);
        if (!$user)
            $this->error(__('用户不存在'));

        if ($user['mobile'])
            $this->error(__('您已经绑定过手机号了'));

        $user->mobile = $mobile;
        $result = $user->save();

        if ($result)
            $this->success(__('绑定成功'));
        else
            $this->error(__('绑定失败'));
    }

    /**
     * @ApiTitle    (手机号登录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 10:32)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/mobileLogin)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function mobileLogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);

            if ($ret) {
                Sms::flush($mobile, 'mobilelogin');
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }

        } else {
            $this->error('手机号不存在');
            //$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
    }

    /**
     * @ApiTitle    (注册用户)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 14:08)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/className/register)
     * @ApiParams   (name="username", type="string", required=true, description="用户名", sample="")
     * @ApiParams   (name="password", type="string", required=true, description="密码", sample="")
     * @ApiParams   (name="email", type="string", required=false, description="邮箱", sample="")
     * @ApiParams   (name="password", type="string", required=false, description="手机号", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改用户个人信息
     * Author Zhenzh
     * DateTime: 2019/7/31 14:07
     *
     * @ApiTitle    (修改用户个人信息)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/editProfile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="username", type="string", required=false, description="用户名", sample="")
     * @ApiParams   (name="nickname", type="string", required=false, description="昵称", sample="")
     * @ApiParams   (name="birthday", type="string", required=false, description="生日", sample="")
     * @ApiParams   (name="avatar", type="string", required=false, description="头像地址", sample="")
     * @ApiParams   (name="bio", type="string", required=false, description="个人简介", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564640159",
    "data": null
    })
     */
    public function editProfile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        //$gender = $this->request->request('gender');
        $birthday = $this->request->request('birthday');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');

        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }

        if($nickname) $user->nickname = $nickname;
        //if($gender) $user->gender = $gender;
        if($birthday) $user->birthday = $birthday;
        if($bio) $user->bio = $bio;
        if($avatar) $user->avatar = $avatar;

        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeEmail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $email   手机号
     * @param string $captcha 验证码
     */
    public function changeMobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * @ApiTitle    (修改密码)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/changePwd)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="mobile", type="string", required=false, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=false, description="验证码", sample="")
     * @ApiParams   (name="password", type="string", required=false, description="新密码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564640159",
    "data": null
    })
     */
    public function changePwd()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $password = $this->request->request('password');
        $captcha = $this->request->request('captcha');

        if (!$mobile || !$captcha || !$password) $this->error(__('Invalid parameters'));
        if (!Validate::regex($mobile, "^1\d{10}$")) $this->error(__('Mobile is incorrect'));
        if ($mobile != $user['mobile']) $this->error(__('手机号不正确'));

        $ret = Sms::check($mobile, $captcha, 'changePwd');
        if (!$ret) $this->error(__('Captcha is incorrect'));
        Sms::flush($mobile, 'changePwd');

        $ret = $this->auth->changepwd($password, '', true);

        if ($ret) $this->success(__('密码修改成功'));
        else $this->error($this->auth->getError());
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定用户
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetPwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

}
